package com.joker.product.service.impl;

import com.joker.product.domain.*;
import com.joker.product.mapper.SkuDetailMapper;
import com.joker.product.service.IPmsDetailService;
import com.joker.product.service.IPmsSkuInfoService;
import com.joker.product.service.IPmsSpuImagesService;
import com.joker.product.service.IPmsSpuInfoDescService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author lemon
 * @date 2024/12/24 16:33
 **/
@Service
public class PmsDetailServiceImpl implements IPmsDetailService {


    @Autowired
    private IPmsSkuInfoService pmsSkuInfoService;
    @Autowired
    private IPmsSpuImagesService pmsSpuImagesService;
    @Autowired
    private IPmsSpuInfoDescService pmsSpuInfoDescService;
    @Autowired
    private SkuDetailMapper skuDetailMapper;

    @Autowired
    private ThreadPoolExecutor itemThreadPoolExecutor;

    @Override
    public SkuDetailVO getDetailBySkuId(Long skuId) throws ExecutionException, InterruptedException {
        SkuDetailVO skuDetailVO = new SkuDetailVO();

        CompletableFuture<PmsSkuInfo> pmsSkuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            PmsSkuInfo pmsSkuInfo = pmsSkuInfoService.selectPmsSkuInfoBySkuId(skuId);
            skuDetailVO.setPmsSkuInfo(pmsSkuInfo);
            return pmsSkuInfo;
        }, itemThreadPoolExecutor);


        CompletableFuture<Void> pmsSpuImagesFuture = pmsSkuInfoCompletableFuture.thenAcceptAsync((pmsSkuInfo) -> {
            List<PmsSpuImages> pmsSpuImages = pmsSpuImagesService.selectBySpuId(pmsSkuInfo.getSpuId());
            skuDetailVO.setPmsSpuImages(pmsSpuImages);
        }, itemThreadPoolExecutor);


        CompletableFuture<Void> pmsSpuInfoDescFuture = pmsSkuInfoCompletableFuture.thenAcceptAsync((pmsSkuInfo) -> {
            PmsSpuInfoDesc pmsSpuInfoDesc = pmsSpuInfoDescService.selectPmsSpuInfoDescBySpuId(pmsSkuInfo.getSpuId());
            skuDetailVO.setPmsSpuInfoDesc(pmsSpuInfoDesc);
        }, itemThreadPoolExecutor);


        CompletableFuture<Void> saleAttrFuture = CompletableFuture.runAsync(() -> {
            List<SaleAttr> saleAttr = skuDetailMapper.getSaleAttr(skuId);
            skuDetailVO.setSaleAttrs(saleAttr);
        });


        CompletableFuture<Void> groupAttrFuture = CompletableFuture.runAsync(() -> {
            List<GroupAttr> groupAttr = skuDetailMapper.getGroupAttr(skuId);
            skuDetailVO.setGroupAttrs(groupAttr);
        });

        CompletableFuture.allOf(
                pmsSkuInfoCompletableFuture,
                pmsSpuImagesFuture,
                pmsSpuInfoDescFuture,
                saleAttrFuture,
                groupAttrFuture).get();

        return skuDetailVO;
    }
}
